﻿using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using AutoMapper.Internal;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Nasty.Core.Authorization;
using Nasty.Core.Redis;
using Nasty.Core.Registry;
using Nasty.Core.Session;
using Nasty.Core.Attributes;
using Nasty.Core.Config;
using SqlSugar;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using StackExchange.Redis;
using Nasty.Core.Security;
using Amazon.S3;
using Nasty.Core.ActionFilter;
using Quartz;
using Nasty.Core.SuperExtension;
using Nasty.QuartzModule.QuartzTask;
using System.Text.Json;

namespace Nasty.QuartzModule
{
    public class QuartzJobListener : IJobListener
    {
        private readonly SqlSugarClient _client;
        private readonly ILogger<QuartzJobListener> _logger;

        public QuartzJobListener(SqlSugarClient client, ILogger<QuartzJobListener> logger)
        {
            _client = client;
            _logger = logger;
        }

        public string Name => "QuartzJobListener";

        public Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }

        public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }

        public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
        {
            var jobType = context.JobDetail.JobType;
            var attr = jobType.GetCustomAttribute<NastyJobAttribute>();
            if (attr != null && !attr.IsLog) return Task.CompletedTask;

            try
            {
                var result = context.Result;
                var task = context.JobDetail.JobDataMap.Get("Task") as QuartzTask.QuartzTask;

                var data = new QuartzTaskLog()
                {
                    TaskId = task.Id,
                    Result = JsonSerializer.Serialize(result)
                };

                _client.Add(data);
            }
            catch (Exception ex)
            {
                _logger.LogInformation($"记录结果失败：{ex.Message}");
            }

            return Task.CompletedTask;
        }
    }
}
